from models.account import Account, TenantAccountJoin
from core.plugin.manager.exc import PluginDaemonClientSideError

from models.provider import Provider, ProviderModel
import json
from core.helper import encrypter

from extensions.ext_database import db
from services.model_provider_service import ModelProviderService
from core.model_runtime.errors.validate import CredentialsValidateFailedError
from services.plugin.plugin_service import PluginService
import os
admin_email = os.getenv("MAIL_DEFAULT_SEND_FROM")
admin_email = "agent-admin@139.com"

def get_adm_tools():
    adm_account_id = db.session.query(Account).filter(Account.email == admin_email).first().id
    adm_tenant_id = db.session.query(TenantAccountJoin).filter(TenantAccountJoin.account_id == adm_account_id, TenantAccountJoin.role == "owner").first().tenant_id
    plugins = PluginService.list(adm_tenant_id)
    plugin_unique_identifiers = []
    if len(plugins) > 0:
        for plugin in plugins:
            plugin_id = plugin.meta['plugin_unique_identifier']
            plugin_unique_identifiers.append(plugin_id)

    return plugin_unique_identifiers

def install_tool(email: str):
    # get user tenant_id
    account_id = db.session.query(Account).filter(Account.email == email).first().id
    tenant_id = db.session.query(TenantAccountJoin).filter(TenantAccountJoin.account_id == account_id).filter(
        TenantAccountJoin.role == "owner").first().tenant_id

    tools = get_adm_tools()
    if tools:
        for i in tools:
            plugin_unique_identifier = [i]
            try:
                # install
                PluginService.install_from_marketplace_pkg(tenant_id, plugin_unique_identifier)
            except PluginDaemonClientSideError as e:
                raise ValueError(e)

def config_models(email: str):
    # get user tenant_id
    account_id = db.session.query(Account).filter(Account.email == email).first().id
    tenant_id = db.session.query(TenantAccountJoin).filter(TenantAccountJoin.account_id == account_id).filter(
        TenantAccountJoin.role == "owner").first().tenant_id

    # get deepseek/tongyi manager models cred
    adm_account_id = db.session.query(Account).filter(Account.email == admin_email).first().id
    adm_tenant_id = db.session.query(TenantAccountJoin).filter(TenantAccountJoin.account_id == adm_account_id).first().tenant_id
    models = db.session.query(Provider).filter(Provider.tenant_id == adm_tenant_id).all()
    if models:
        for model in models:
            provider = model.provider_name
            # {"api_key":"sk-9f00609xxxxxxx"}
            cfg_json = model.encrypted_config
            cfg = json.loads(cfg_json)
            if provider == "langgenius/tongyi/tongyi":
                key_name = "dashscope_api_key"
            elif provider == "langgenius/deepseek/deepseek":
                key_name = "api_key"
            else:
                raise ValueError("api_key name not match")
            en_api_key = cfg[key_name]
            api_key = encrypter.decrypt_token(adm_tenant_id,en_api_key)
            credentials = {}
            credentials[key_name] = api_key
            model_provider_service = ModelProviderService()
            try:
                model_provider_service.save_provider_credentials(
                    tenant_id=tenant_id, provider=provider, credentials=credentials
                )
            except CredentialsValidateFailedError as ex:
                raise ValueError(str(ex))

    return {"result": "success"}, 201

def config_ollama_models(email: str):
    # get user tenant_id
    account_id = db.session.query(Account).filter(Account.email == email).first().id
    tenant_id = db.session.query(TenantAccountJoin).filter(TenantAccountJoin.account_id == account_id).filter(
        TenantAccountJoin.role == "owner").first().tenant_id

    # get deepseek/tongyi manager models cred
    adm_account_id = db.session.query(Account).filter(Account.email == admin_email).first().id
    adm_tenant_id = db.session.query(TenantAccountJoin).filter(TenantAccountJoin.account_id == adm_account_id).first().tenant_id
    models = db.session.query(ProviderModel).filter(ProviderModel.tenant_id == adm_tenant_id).all()
    if models:
        for model in models:
            provider = model.provider_name
            model_name = model.model_name
            model_type = model.model_type
            credentials = model.encrypted_config
            try:
                model_provider_service = ModelProviderService()
                model_provider_service.save_model_credentials(
                    tenant_id=tenant_id,
                    provider=provider,
                    model=model_name,
                    model_type=model_type,
                    credentials=json.loads(credentials),
                )
            except CredentialsValidateFailedError as ex:
                logging.exception(
                    f"Failed to save model credentials, tenant_id: {tenant_id},"
                    f" model: {args.get('model')}, model_type: {args.get('model_type')}"
                )
                raise ValueError(str(ex))